import services from '@/services/user';
import { EUser } from '@/services/user/UserController';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { message, Modal, Typography } from 'antd';
import React, { PropsWithChildren } from 'react';

export interface Props {
  onCancel: (show?: boolean) => void;
  onReloadAndRest?: () => void;
  modalVisible: boolean;
  user?: EUser;
}

const { editTechnically } = services.UserController;
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在更新');
  try {
    const { success, errorMessage } = await editTechnically(fields);
    hide();
    if (success) {
      message.success('更新成功');
      return true;
    } else {
      message.error(errorMessage);
      return false;
    }
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};
const UpdateTechnicallyForm: React.FC<PropsWithChildren<Props>> = (props) => {
  const { modalVisible, onCancel, onReloadAndRest, user } = props;
  const [allTechnically, setAllTechnically] = React.useState<string>('');

  return (
    <Modal
      destroyOnClose
      title="编辑会员水平分"
      width={420}
      open={modalVisible}
      onCancel={() => onCancel(false)}
      footer={null}
    >
      <ProForm<Record<string, string>>
        onFinish={async (values) => {
          const success = await handleUpdate(values);
          if (success) {
            onReloadAndRest?.();
          }
        }}
      >

        <Typography.Paragraph>{`${user?.name}当前水平分：`}<Typography.Text type="success">{`${user?.technically ?? 0}`}</Typography.Text></Typography.Paragraph>

        <ProFormText name="userId" hidden initialValue={user?.userId} />
        <ProFormText
          width="md"
          name="newTechnically"
          label="新增水平分"
          rules={[
            {
              required: true,
              message: '请输入水平分!',
            },
          ]}
          fieldProps={{
            onChange: txt => {
              if (txt.target.value === '') {
                setAllTechnically('')
              } else {
                var v = (parseFloat(txt.target.value) + (user?.technically ?? 0))
                setAllTechnically(`${v}`)
              }
            }
          }}
        />
        <Typography.Paragraph>调整后水平分：<Typography.Text type="danger">{`${allTechnically}`}</Typography.Text></Typography.Paragraph>
        <ProFormText
          width="md"
          name="reason"
          label="原因"
          rules={[
            {
              required: true,
              message: '请输入原因!',
            },
          ]}
        />
      </ProForm>
    </Modal>
  );
};

export default UpdateTechnicallyForm;
